package proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import model.RpcRequest;
import model.RpcResponse;
import serializer.JdkSerializer;
import serializer.Serializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Author: mengyu
 * @Date: 2024/7/14
 * 动态代理
 */
public class ServiceProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 指定序列化器
        Serializer serializer = new JdkSerializer();
        // 构建 RpcRequest
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setServiceName(method.getDeclaringClass().getName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setParameterTypes(method.getParameterTypes());
        rpcRequest.setArgs(args);

        // 发送请求
        String url = "localhost:8080";
        try {
            // 序列化
            byte[] serialize = serializer.serialize(rpcRequest);
            // 发送
            try(HttpResponse httpResponse = HttpRequest.post(url)
                    .body(serialize)
                    .execute()){
                byte[] bytes = httpResponse.bodyBytes();
                // 反序列化
                RpcResponse deserialize = serializer.deserialize(bytes, RpcResponse.class);
                return deserialize.getDate();
            }

        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
